import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import type { RouteMeta } from '@/types'

// 定义路由
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/chat'
  },
  {
    path: '/chat',
    name: 'AIChatPage',
    component: () => import('@/views/AIChatPage.vue'),
    meta: {
      requiresAuth: true,
      title: 'AI情感助手'
    } as RouteMeta
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/LoginView.vue'),
    meta: {
      requiresGuest: true,
      title: '用户登录'
    } as RouteMeta
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/RegisterView.vue'),
    meta: {
      requiresGuest: true,
      title: '用户注册'
    } as RouteMeta
  },
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: () => import('@/views/auth/ResetPasswordView.vue'),
    meta: {
      requiresGuest: true,
      title: '重置密码'
    } as RouteMeta
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/DashboardView.vue'),
    meta: {
      requiresAuth: true,
      title: '控制台'
    } as RouteMeta
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/ProfileView.vue'),
    meta: {
      requiresAuth: true,
      title: '个人资料'
    } as RouteMeta
  },
  {
    path: '/voice-settings',
    name: 'VoiceSettings',
    component: () => import('@/views/VoiceSettingsView.vue'),
    meta: {
      requiresAuth: true,
      title: '语音设置'
    } as RouteMeta
  },
  {
    path: '/test-profile-api',
    name: 'TestProfileAPI',
    component: () => import('@/views/TestProfileAPI.vue'),
    meta: {
      requiresAuth: true,
      title: 'API测试'
    } as RouteMeta
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFoundView.vue'),
    meta: {
      title: '页面未找到'
    } as RouteMeta
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 设置页面标题
const setPageTitle = (title?: string) => {
  const baseTitle = 'AI角色扮演语音聊天'
  document.title = title ? `${title} - ${baseTitle}` : baseTitle
}

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  setPageTitle(to.meta?.title as string)
  
  // 初始化认证状态（仅在首次访问时）
  if (!authStore.isAuthenticated && !authStore.loading) {
    try {
      await authStore.initAuth()
    } catch (error) {
      console.error('Failed to initialize auth:', error)
    }
  }
  
  const { requiresAuth, requiresGuest } = to.meta as RouteMeta
  
  // 需要登录的页面
  if (requiresAuth && !authStore.isAuthenticated) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 只允许游客访问的页面（如登录、注册页面）
  if (requiresGuest && authStore.isAuthenticated) {
    next('/chat')
    return
  }
  
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 可以在这里添加页面访问统计、埋点等逻辑
  console.log(`Navigation: ${from.path} -> ${to.path}`)
})

export default router
